package cn.wsalix.spring;

import java.util.Map;
import java.util.Properties;

import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.registry.internal.StandardServiceRegistryImpl;
import org.hibernate.cfg.Environment;
import org.hibernate.internal.util.config.ConfigurationHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.WebApplicationContext;

import cn.wsalix.config.AppConfig;
import cn.wsalix.config.SysConfig;
import cn.wsalix.constant.Global;
import cn.wsalix.init.ProjectInit;
import cn.wsalix.web.GlobalWeb;
import cn.wsalix.weixin.service.WxConfigService;
import cn.wsalix.weixin.service.WxService;

@Component("beanDefineConfigue")
public class BeanDefineConfigue implements
		ApplicationListener<ContextRefreshedEvent> {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private String hwHello;
	@Autowired
	private SysConfig sysConfig;

	@Value("${qq.app.id}")
	private String qqAppId;

	@Value("${qq.app.key}")
	private String qqAppKey;

	@Value("${qq.server.name}")
	private String qqServerName;

	@Value("${wx.app.id}")
	private String wxAppId;
	@Value("${wx.mch_id}")
	private String wxMchId;
	@Value("${wx.trade_type}")
	private String wxTradeType;
	@Value("${wx.notify_url}")
	private String wxNotifyUrl;
	@Value("${wx.pay.Key}")
	private String wxPayKey;

	@Value("${urlSuffix}")
	private String urlSuffix;

	@Autowired
	private AppConfig appConfig;
	@Autowired
	private ProjectInit projectInit;
	@Autowired
	private WxService wxService;
	@Autowired
	private LocalContainerEntityManagerFactoryBean entityManagerFactory;
	@Autowired
	private SpringUtils springUtils;
	@Autowired
	private WxConfigService wxConfigService;
	/**
	 * @param event
	 *            进入两次,event.getApplicationContext().getParent()一次为Null,<br>
	 *            完成后跳转 @WebInit 完成后跳回 再次进入，第二次不为Null,第二次可以获取RequestMapping
	 */
	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		if (event.getApplicationContext().getParent() == null) {
			// instanceof
			Global.springContext = event.getApplicationContext();
			GlobalWeb.appConfig = appConfig;
			GlobalWeb.sysConfig = sysConfig;
			// Global.version = version;
			Global.qqAppId = qqAppId;
			Global.qqAppKey = qqAppKey;
			Global.qqServerName = qqServerName;
			Global.urlSuffix = urlSuffix;
			Global.wxAppId = wxAppId;
			Global.wxMchId = wxMchId;
			Global.wxTradeType = wxTradeType;
			Global.wxNotifyUrl = wxNotifyUrl;
			Global.wxPayKey = wxPayKey;
			/*
			 * int wxCount = userService.findWxUserCount(); Global.wxUserCount =
			 * new AtomicInteger(wxCount);
			 * 
			 * FileServerConfig fsConfig = new FileServerConfig();
			 * fsConfig.setSaveDir(uploadDir);
			 * fsConfig.setGenFileName(GenFileName.Timestamp);
			 * fsConfig.setServerType(FileServer.Local);
			 * fsConfig.setHttpPrix(uploadHttp);//
			 * "http://192.168.1.107/upload/");
			 * 
			 * // root application context 没有parent，他就是老大. //
			 * 需要执行的逻辑代码，当spring容器初始化完成后就会执行该方法。 Global.uploadDir = uploadDir;
			 * Global.uploadHttp = uploadHttp; Global.urlSuffix = urlSuffix;
			 * Global.templetPath = templetPath;
			 * Global.siteTempletPath=siteTempletPath; Global.fsConfig =
			 * fsConfig;
			 */

			// Global.singleConfig = singleConfig;
			// StandardServiceRegistryImpl serviceRegistry =
			// createServiceRegistry( cfg.getProperties() );
		} else {
			Boolean isTrue = (event.getApplicationContext() instanceof WebApplicationContext);
			logger.info("" + isTrue);
			springUtils.traverse(event.getApplicationContext()
					.getBeansWithAnnotation(Controller.class));
			// springUtils.traverse(RequiresRoles.class, requiresRolesTraverse);
			// springUtils.traverse(RequiresPermissions.class,
			// requiresPermissionsTraverse);

			Map<String, Object> jpaMap = entityManagerFactory
					.getJpaPropertyMap();
			boolean isCreate=jpaMap.get("hibernate.hbm2ddl.auto").equals("create");
			projectInit.initCheck(isCreate);
			if (isCreate) {
				
				// 数据初始化
				// 用户初始化
				// 菜单初始化
				// 角色初始化
				/**
				 * 不能直接获取RequestMapping Map<String, Object> requestMappingBeans
				 * = event.getApplicationContext()
				 * .getBeansWithAnnotation(RequestMapping.class); for (Object
				 * bean : requestMappingBeans.values()) {
				 * System.err.println(bean == null ? "null" : bean.getClass()
				 * .getName()); } // 角色 不能直接获取RequiresRoles Map<String, Object>
				 * roleBeans = event.getApplicationContext()
				 * .getBeansWithAnnotation(RequiresRoles.class); for (Object
				 * bean : roleBeans.values()) { System.err.println(bean == null
				 * ? "null" : bean.getClass() .getName()); } // 权限 Map<String,
				 * Object> permitBeans = event.getApplicationContext()
				 * .getBeansWithAnnotation(RequiresPermissions.class); for
				 * (Object bean : permitBeans.values()) {
				 * System.err.println(bean == null ? "null" : bean.getClass()
				 * .getName()); }
				 */
				System.err.println("=====ContextRefreshedEvent====="
						+ event.getSource().getClass().getName());
				// projectInit.start();
			}
		}
		logger.info("==========finish");
	}

	private static StandardServiceRegistryImpl createServiceRegistry(
			Properties properties) {
		Environment.verifyProperties(properties);
		ConfigurationHelper.resolvePlaceHolders(properties);
		return (StandardServiceRegistryImpl) new StandardServiceRegistryBuilder()
				.applySettings(properties).build();
	}
}
